const {queryFileSql, deleteFileOneSql} = require("../../../model/commonModel");
const responseResult = require("../../../util/responseResult");
const {Router} = require("express");
const fs = require("fs");
const deleteAvatarRouter = Router();
const pathModule = require("path");
deleteAvatarRouter.get("/:id", (req, res, next) => {
    const {id} = req.params;
    queryFileSql({id}, res, (results) => {
        if (results.length) {
            const {path, id} = results[0];//查询到的路径和id
            const start = path.indexOf("load/") + 5;//开始索引
            const firstStr = path.slice(0, start);//获取除名字外的所有字符串
            const fileName = path.replace(firstStr, "");//替换
            let filePath = pathModule.join(`${__dirname}+../../../../upload/${fileName}`);
            // 规范路径
            filePath = pathModule.normalize(filePath);
            console.log(filePath);
            deleteFileOneSql({id}, res, () => {
                // 成功执行执行
            })
            // 删除文件
            fs.unlink(filePath, err => {
                if (err) {
                    // 失败
                    return res.json(responseResult.error("头像信息不存在，无需清除"));
                }
                return res.json(responseResult.success("头像信息已清除"));
            });
        } else {
            return res.json(responseResult.error("头像信息不存在，无需清除"))
        }
    })
})

module.exports = deleteAvatarRouter;
